<template>
  <div class="form-box">
    <el-form :model="model" :rules="rules" ref="model" label-width="100px" class="demo-ruleForm">
      <el-form-item label="岗位权限：" prop="groupName">
        <el-input v-model="model.groupName"></el-input>
      </el-form-item>
      <el-form-item label="岗位名称：" prop="checkMenu">
        <el-tree
          :data="treeList"
          show-checkbox
          node-key="id"
          ref="tree"
          :default-checked-keys="defaultCheckMenu"
          :props="defaultProps">
        </el-tree>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('model')">{{$t('action.comfirm')}}</el-button>
        <el-button @click="close">{{$t('action.cancel')}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {mapState} from "vuex"

  export default {
    name: "AddPost",
    props: ["id", "closePop"],
    data() {
      var checkIsCheckedMenu = (rule, value, callback) => {
        if (!this.$refs.tree.getCheckedNodes().length) return callback(new Error('请选择链接类型'));
        return true
      };
      return {
        model: {
          groupName: ""
        },
        defaultCheckMenu: [],
        defaultProps: {
          children: 'children',
          label: 'name',
        },
        rules: {
          groupName: [
            {required: true, message: '请输入岗位名称', trigger: 'blur'},
          ],
          checkMenu: [
            {required: true, message: "请选择菜单", trigger: 'blur', validator: checkIsCheckedMenu},
          ],
        },
      }
    },
    computed: {
      ...mapState({
        treeList: state => state.menu.navTree
      })
    },
    created() {
      this.init(this.id || this.$route.query.id);
    },
    methods: {
      init() {
        this.getTreeList()
      },
      getTreeList(id) {
        this.$api.account.getAccountGroupMenu({"groupId": id}).then(
          res => {
            res.data.list.map(
              item => {
                this.defaultCheckMenu.push(item.id)
              }
            )
          }
        )
      },
      getCheckedNodes(leafOnly, includeHalfChecked) {
        console.log(leafOnly, includeHalfChecked)
      },
      onSubmit(formName) {
        console.log(this.$refs[formName])
        this.$refs[formName].validate((valid) => {
          console.log(valid)
          if (valid) {
            this.$message({
              type: 'success',
              message: '编辑成功'
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      close(data){
        this.$emit("closePop",data)
      }
    },
  }
</script>

<style lang="scss" scoped>
  .form-box {
    margin: 10px;
    border-radius: 2px;
    background-color: #fff;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .05);
    padding: 10px;
  }
  .el-form {
    width: 60%;
    margin: 0 auto
  }
</style>
